package com.tanhua.manage.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.json.JSONUtil;
import com.tanhua.commons.utils.Constants;
import com.tanhua.manage.service.ManageLoginService;
import com.tanhua.model.vo.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/manage")
public class ManageLoginController {
    @Autowired
    private ManageLoginService manageLoginService;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @GetMapping("/verification")
    public void verification(String uuid,HttpServletResponse response) throws IOException {

        //通过工具类生成验证码图片
        LineCaptcha captcha = CaptchaUtil.createLineCaptcha(229, 97);//指定验证码的尺寸
        //获取验证码内容
        String code = captcha.getCode();
        //将验证码存到redis中
        String key= Constants.CAP_CODE+uuid;
        redisTemplate.opsForValue().set(key,code,5, TimeUnit.MINUTES);
        //将图片返回
        captcha.write(response.getOutputStream());
    }

    @PostMapping("/loginVerification")
    public ResponseEntity loginVerification(@RequestBody Map map){

        //获取参数
        String username = (String) map.get("username");
        String password = (String) map.get("password");
        String code = (String) map.get("code");
        String uuid = (String) map.get("uuid");
        //调用service
        String token=manageLoginService.loginVerification(username,password,code,uuid);
        Map retmap=new HashMap();
        retmap.put("token",token);
        return ResponseEntity.ok(retmap);
    }

    //查询所有用户
    @GetMapping("/users/findByPage")
    public ResponseEntity findUsers(@RequestParam(defaultValue = "1") Integer page,
                                    @RequestParam(defaultValue = "10") Integer pageSize){
        PageResult vo=manageLoginService.findAll(page,pageSize);
        String jsonStr = JSONUtil.toJsonStr(vo);
        return ResponseEntity.ok(jsonStr);
    }

    @GetMapping("/users/findLocation")
    public ResponseEntity findLocation(String userId){
        List<String> list =manageLoginService.findLocation(userId);
        System.out.println(list);
        return ResponseEntity.ok(list);

    }
}
